package com.dbflow5.query;

import com.dbflow5.query.property.IProperty;
import com.dbflow5.sql.Query;

/**
 * Description: Represents an individual condition inside a CASE.
 */
public class CaseCondition<TReturn> implements Query {

    private final Case<TReturn> caze;
    private final TReturn whenValue;
    private final SQLOperator sqlOperator;
    private TReturn thenValue;
    private final IProperty<?> property;
    private IProperty<?> thenProperty = null;
    private boolean isThenPropertySet;

    @Override
    public String getQuery() {
        StringBuilder builder = new StringBuilder();
        builder.append(" WHEN ");
        if (caze.isEfficientCase) {
            builder.append(BaseOperator.convertValueToString(property == null? whenValue : property, false));
        } else {
            if(sqlOperator != null){
                sqlOperator.appendConditionToQuery(builder);
            }
        }
        builder.append(" THEN ");
        builder.append(BaseOperator.convertValueToString(isThenPropertySet? thenProperty : thenValue, false));

        return builder.toString();
    }

    public CaseCondition(Case<TReturn> caze, SQLOperator sqlOperator) {
        this.caze = caze;
        this.sqlOperator = sqlOperator;
        this.whenValue = null;
        this.property = null;
    }

    public CaseCondition(Case<TReturn> caze, TReturn whenValue) {
        this.caze = caze;
        this.whenValue = whenValue;
        this.sqlOperator = null;
        this.property = null;
    }

    public CaseCondition(Case<TReturn> caze, IProperty<?> property) {
        this.caze = caze;
        this.property = property;
        this.whenValue = null;
        this.sqlOperator = null;
    }

    /**
     * THEN part of this query, the value that gets set on column if condition is true.
     *
     * @param value value
     * @return caze
     */
    public Case<TReturn> then(TReturn value) {
        thenValue = value;
        return caze;
    }

    public Case<TReturn> then(IProperty<?> value) {
        thenProperty = value;

        // in case values are null in some sense.
        isThenPropertySet = true;
        return caze;
    }

    @Override
    public String toString() {
        return getQuery();
    }
}
